import { Module } from '@nestjs/common';
import { MulterModule } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname, join } from 'path';
import { UploadService } from './upload.service';
import { UploadController } from './upload.controller';

@Module({
  imports: [
    MulterModule.register({
      // 图片上传后要存放的位置
      storage: diskStorage({
        destination: (req, file, cb) => {
          const fileExt = extname(file.originalname)
          let uploadPath = 'static/grocery/files'

          if (['.jpg', '.jpeg', '.png', '.gif', '.webp'].includes(fileExt)) {
            uploadPath = 'static/grocery/imgs'
          }
          cb(null, uploadPath)
        },
        filename: (req, file, cb) => {
          const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1E9)}`
          cb(null, `${file.fieldname}-${uniqueSuffix}${extname(file.originalname)}`)
        }
      }),
    }),
  ],
  controllers: [UploadController],
  providers: [UploadService],
})
export class UploadModule {}
